<?php

namespace App\Jobs;

use App\Models\Mysql\XnOrder;
use Exception;
use Illuminate\Bus\Queueable;
use App\Models\Admin\Supplier;
use Illuminate\Support\Facades\Log;
use Illuminate\Queue\SerializesModels;
use App\Recharge\Service\CycleService;
use App\Recharge\Traits\RechargeTraits;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Recharge\Service\DirectChargingService;
use App\Jobs\Middleware\SupplierDbConnectCheck;
use App\Recharge\Service\CombinationProductsService;
use Throwable;


class ApiRechargeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, RechargeTraits;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(public Supplier $supplier, public XnOrder $order){}

    /**
     * @return array
     */
    public function middleware(): array
    {
        return [new SupplierDbConnectCheck($this->supplier)];
    }

    /**
     * 充值
     *
     * @return void
     */
    public function handle(): void
    {
        try {
            match ($this->order->goods_belong) {
                1 => throw new Exception("人工代充不继续往下走"),
                2 => CycleService::new($this->supplier, $this->order)->execute(),
                3 => CombinationProductsService::new($this->supplier, $this->order)->execute(),
                default => DirectChargingService::new($this->supplier, $this->order)->execute(),
            };
        } catch (Throwable $e) {
            Log::channel('job')->error($e->getMessage(), [
                'supplier' => $this->supplier->toArray(),
                'order'    => $this->order->toArray(),
            ]);
        }
    }
}

